package com.lanyuan.controller.system;

import com.lanyuan.controller.index.BaseController;
import com.lanyuan.util.DateUtil;
import com.lanyuan.util.FileUtil;
import com.lanyuan.util.PropertiesUtils;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

@Controller
public class UploadController extends BaseController {

    @ResponseBody
    @RequestMapping("/system/upload")
    public String upload(
            @RequestParam(value = "file") MultipartFile file
    ) throws Exception {
        // 1、上传对帐文件到upload目录
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //String parameter = request.getParameter("starPosinfoMap.postype");
        String UploadFileName = file.getOriginalFilename();// 文件原名
        // String 类型
        if (UploadFileName.equals("")) {
            return "401";
        }
        String filesize = Long.toString(file.getSize());// 文件大小 存为

        // 上传文件路径
        String pass2 = DateUtil.formatDate();
        String pass = "/uploadFile" + File.separator + "imageai" + File.separator + pass2;
        String realPath = pass;//生产服务器
        //String realPath = request.getServletContext().getRealPath(pass);//本地服务器
        System.out.println("realPath:"+realPath);
       /* String uploadFilePath = "/uploadFile";//PropertiesUtils.findPropertiesKey("upload-file-path");
        if (StringUtils.isNotEmpty(uploadFilePath)) {
            realPath = uploadFilePath + File.separator + "imageai" + File.separator + pass2;
        }*/

        // 这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
        FileUtils.forceMkdir(new File(realPath));
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, UploadFileName));
        // 2、重命名对帐文件
        String suffix = UploadFileName.substring(UploadFileName.lastIndexOf(".") + 1);

        String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String newFileName = datetime + "-" + (UUID.randomUUID().toString().replaceAll("-", "")) + "." + suffix; // 新对帐文件名
        newFileName = newFileName.toLowerCase();
        String resFilePathAndFile = realPath + File.separator + UploadFileName;
        FileUtil.renameFile(resFilePathAndFile, newFileName); // 重命名文件
        System.out.println("文件上传：" + realPath + ">" + UploadFileName + ">" + newFileName);
        return "/uploadFile/" + "imageai" + "/" + pass2 + "/" + newFileName;
    }

    @ResponseBody
    @RequestMapping("/system/uploadImage2")
    public void uploadImage2(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter writer=null;
        String callback = request.getParameter("CKEditorFuncNum");
        try {


            writer = response.getWriter();
            // 1、上传对帐文件到upload目录
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getServletContext());
            if (multipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

                //遍历上传
                Iterator<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile((String) iter.next());

                    String UploadFileName = file.getOriginalFilename();// 文件原名

                    String filesize = Long.toString(file.getSize());// 文件大小 存为

                    // 上传文件路径
                    String pass2 = DateUtil.formatDate();
                    String pass = "/uploadFile" + File.separator + "imageai" + File.separator + pass2;
                    String realPath = pass;//生产服务器
                    //String realPath = request.getServletContext().getRealPath(pass);//本地服务器
                    System.out.println("realPath:"+realPath);

//                    String uploadFilePath = "/uploadFile";
//                    if (StringUtils.isNotEmpty(uploadFilePath)) {
//                        realPath = uploadFilePath + File.separator + "imageai" + File.separator + pass2;
//                    }

                    // 这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
                    FileUtils.forceMkdir(new File(realPath));
                    FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, UploadFileName));
                    // 2、重命名对帐文件
                    String suffix = UploadFileName.substring(UploadFileName.lastIndexOf(".") + 1);

                    String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                    String newFileName = datetime + "-" + (UUID.randomUUID().toString().replaceAll("-", "")) + "." + suffix; // 新对帐文件名
                    newFileName = newFileName.toLowerCase();
                    String resFilePathAndFile = realPath + File.separator + UploadFileName;
                    FileUtil.renameFile(resFilePathAndFile, newFileName); // 重命名文件
                    System.out.println("文件上传：" + realPath + ">" + UploadFileName + ">" + newFileName);
                    String url= "/uploadFile/" + "imageai" + "/" + pass2 + "/" + newFileName;
                    JSONObject obj = new JSONObject();
                    obj.put("uploaded", 1);
                    obj.put("url", this.getServerUrl(request)+url);
                    obj.put("fileName",UploadFileName);
                    writer.println(obj.toString());
                }
            }
        }catch (Exception e){
            e.printStackTrace();

        }

    }
    public  String getServerUrl(HttpServletRequest request) {
        // 访问协议
        String agreement = request.getScheme();
        // 访问域名
        String serverName = request.getServerName();
        // 访问端口号
        int port = request.getServerPort();
        // 访问项目名
        String contextPath = request.getContextPath();
        String url = "%s://%s%s%s";
        String portStr = "";
        if (port != 80) {
            portStr += ":" + port;
        }
        return String.format(url, agreement, serverName, portStr, contextPath);

    }
}
